package flexo.gui;

import flexo.graphic.Color;
import flexo.graphic.Font;
import flexo.graphic.GraphicSystem;
import flexo.graphic.entity.Text;
import flexo.math.Coords;
import flexo.scene.Node;

public class Label extends Widget
{
	protected Color fontColor;
	protected Text text;

	public Label(String name, Coords size, String font)
	{
		super(name, size);
		this.fontColor = new Color(1,1,1,1);
		GraphicSystem gs = (GraphicSystem)flexo.Kernel.getSystem(GraphicSystem.ID);
		Font fontDesc;
		if (gs.existsFont(font))
		{
			fontDesc = gs.getFont(font);
		}
		else
		{
			fontDesc = gs.addFont(font);
		}
		
		Coords maxCharSize = new Coords();
		maxCharSize.x = size.y * fontDesc.getAveragedAspectRatio();
		maxCharSize.y = size.y;
		
		// Calculate how many chars fit in the area
		maxCharSize.x = (int)(size.x / maxCharSize.x);
		maxCharSize.y = 1;
		int maxChars = (int)(maxCharSize.x * maxCharSize.y);
		
		// Initialize text entity
		text = gs.addText(font, maxChars);
		text.setSize(size.y);
		text.setMaterial(fontDesc.getDefaultMaterial());
	}

	public void setColor(Color fontColor)
	{
		this.fontColor = fontColor;
		text.setColor(this.fontColor);
	}
	
	public void setText(String text)
	{
		this.text.setText(text);
		this.text.setColor(fontColor);
	}
	
	@Override
	public boolean attachTo(Node n)
	{
		boolean result = super.attachTo(n);
		if (result)
		{
			text.attachTo(n);
		}
		return result;
	}
	
	@Override
	public void deattachFrom(Node n)
	{
		text.deattachFrom(n);
		super.deattachFrom(n);		
	}
}
